package org.smarthings.coap;

import java.util.List;

import org.eclipse.californium.core.CoapServer;
import org.eclipse.californium.core.coap.Response;
import org.eclipse.californium.core.network.Exchange;
import org.eclipse.californium.core.server.MessageDeliverer;
import org.eclipse.californium.core.server.resources.Resource;
import org.smarthings.Server;

public class CoapServerImpl implements Server, MessageDeliverer {
	private MessageDeliverer messageDeliverer;
	private CoapServer server;

	public void start(String host, int port) {
		server = new CoapServer(port);
		messageDeliverer = server.getMessageDeliverer();
		server.setMessageDeliverer(this);
		server.start();
		System.out.println(CoapFactory.PROTOCOL + " SERVER STARTED");
	}

	public void stop() {
		server.stop();
		System.out.println(CoapFactory.PROTOCOL + " SERVER STOPPED");
	}

	public String getProtocol() {
		return CoapFactory.PROTOCOL;
	}

	public void update(String uri) {
		String[] paths = uri.split("/");
		Resource node = server.getRoot();
		for (String path : paths) {
			Resource child = node.getChild(path);
			if (child == null) {
				return;
			}
			node = child;
		}

		if (node instanceof CoapResourceImpl) {
			((CoapResourceImpl) node).changed();
		}
	}

	public void deliverRequest(Exchange exchange) {
		List<String> paths = exchange.getRequest().getOptions().getURIPaths();
		Resource node = server.getRoot();
		for (String path : paths) {
			Resource child = node.getChild(path);
			if (child == null) {
				child = new CoapResourceImpl(path);
				node.add(child);
			}
			node = child;
		}
		messageDeliverer.deliverRequest(exchange);
	}

	public void deliverResponse(Exchange exchange, Response response) {
		messageDeliverer.deliverResponse(exchange, response);
	}
}
